package com.sz.zhiling.common;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.IOException;

//工具类，专门处理http协议的get，post方法
public class HttpClientUtils {

    private static Logger logger = Logger.getLogger(HttpClientUtils.class);

    //获取token的方法
    public static String getTokenMethod(String url) {
        String result = getMethod(url);
        Object obj = JSON.parse(result);
        JSONObject json = (JSONObject) obj;
        Object access_token = json.get("access_token");
        //提取需要的access_token;
        result = (String) access_token;
        return result;//token
    }





    //通用get方法
    public static String getMethod(String url){
        String result = "";
        //定义一个客户端
        HttpClient client = HttpClients.createDefault();
        //准备发送get请求
        HttpGet get = new HttpGet(url);
        try {
            //正式执行get请求,得到服务端的响应
            HttpResponse response = client.execute(get);
            //得到状态码
            logger.debug(response.getStatusLine());
            //响应内容
            HttpEntity entity = response.getEntity();
            //解析响应的结果为字符串
            result = EntityUtils.toString(entity,"UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;//token
    }


    //通用post方法
    public static String postMethod(String url,String json){
        String result = "";
        //定义一个客户端
        HttpClient client = HttpClients.createDefault();
        //准备发送post请求
        HttpPost post = new HttpPost(url);
        try {
            //设置请求字符编码
            StringEntity stringEntityentity = new StringEntity(json,"UTF-8");
            //设置请求头信息
            post.setHeader("content-type","application/json,charset=UTF-8");
            //设置请求体
            post.setEntity(stringEntityentity);
            //正式执行get请求,得到服务端的响应
            HttpResponse response = client.execute(post);
            //得到状态码
            logger.debug(response.getStatusLine());
            //响应内容
            HttpEntity entity = response.getEntity();
            //解析响应的结果为字符串
            result = EntityUtils.toString(entity,"UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;//token
    }


}
